package com.qkbb.admin.kuibu.qkbb.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qkbb.admin.kuibu.R;
import com.qkbb.admin.kuibu.adapter.FriendListAdapter;
import com.qkbb.admin.kuibu.qkbb.JavaBean.FriendList;
import com.qkbb.admin.kuibu.qkbb.JavaBean.InVite;
import com.qkbb.admin.kuibu.qkbb.activity.FindFriend;
import com.qkbb.admin.kuibu.qkbb.activity.MeetFriend;
import com.qkbb.admin.kuibu.qkbb.funcation.GetFriendList;
import com.qkbb.admin.kuibu.qkbb.funcation.HttpURLConnHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.SDCardHelper;
import com.qkbb.admin.kuibu.qkbb.sortlistview.CharacterParser;
import com.qkbb.admin.kuibu.qkbb.sortlistview.ClearEditText;
import com.qkbb.admin.kuibu.qkbb.sortlistview.PinyinComparator;
import com.qkbb.admin.kuibu.qkbb.sortlistview.SideBar;
import com.qkbb.admin.kuibu.qkbb.sortlistview.SortAdapter;
import com.qkbb.admin.kuibu.qkbb.sortlistview.SortModel;
import com.qkbb.admin.kuibu.qkbb.url.Url;
import com.qkbb.admin.kuibu.qkbb.view.CustomProgressDialog;
import com.qkbb.admin.kuibu.qkbb.view.TitleBarView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by admin on 2016/1/27.
 */
public class Friend_fragment extends Fragment {
    private TitleBarView titleBarView;
    private ListView listview;
    private RelativeLayout relativeLayout;
    private Handler handler;
    private List<InVite> inViteList;
    CustomProgressDialog progressDialog;
    /**
     * 显示字母的TextView
     */
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private View view;
    private SideBar sideBar;
    private ListView sortListView;
    private String user_token;
    private ArrayList<SortModel> mSortList;
    private View v;
    private LinearLayout linearLayout;
    private TextView textView;
    private int num;
    private String result;
    private String pinyin;
    private String name;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         view=inflater.inflate(R.layout.fragment_friend,null);
        user_token= SDCardHelper.loadFileFromSdCard("user_token",getActivity());
        titleBarView=(TitleBarView)view.findViewById(R.id.friend_list_titlebar);
        titleBarView.setCenterTexiView("好友");
        titleBarView.settextColor(Color.WHITE);
        titleBarView.setRightButton(R.mipmap.addfriend);
        progressDialog=CustomProgressDialog.createDialog(getActivity());
        progressDialog.show();
        titleBarView.setRightButtonClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), FindFriend.class);
                startActivity(intent);
            }
        });

        initViews();
        return view;
    }
    private void initViews() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        textView= (TextView) view.findViewById(R.id.friend_first_num);
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        linearLayout= (LinearLayout) view.findViewById(R.id.fragment_friend_linearlayout);
        sideBar.setTextView(dialog);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), MeetFriend.class);
                intent.putExtra("result",result);
                startActivity(intent);
        }
        });
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });
        filledData();
        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        getInvite();
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                if (position==0){

                }
            }
        });
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==1){
                    SourceDateList =mSortList;
                    Log.e("finish","finish");
                    // 根据a-z进行排序源数据
                    Collections.sort(SourceDateList, pinyinComparator);
                    adapter = new SortAdapter(getActivity(), SourceDateList);
                    sortListView.setAdapter(adapter);
                    progressDialog.cancel();
                }
                if (msg.what==2){
                    textView.setText(num+"");
                }
            }
        };



        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);
        boolean flage=(mClearEditText == null);
        Log.e("flage", flage + "");
        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    private  void getInvite(){
        inViteList=new ArrayList<InVite>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte b[]=HttpURLConnHelper.loadByteFromURL(Url.GETINVITE+user_token,getActivity());
                if (b!=null){
                    result=new String(b);
                    Log.e("result",result);
                    JSONObject jsonObject= null;
                    try {
                        jsonObject = new JSONObject(result);
                        JSONObject jsonObject1=jsonObject.getJSONObject("data");
                        JSONArray jsonArray=jsonObject1.getJSONArray("invitations");
                        num=jsonArray.length();
                        Message message=new Message();
                        message.what=2;
                        handler.sendMessage(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();

    }



    /**
     * 为ListView填充数据
     *
     * @return
     */
    private List<SortModel> filledData(){

        mSortList = new ArrayList<SortModel>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte b[]= HttpURLConnHelper.loadByteFromURL(Url.GETFRIEND+user_token,getActivity());
                if (b!=null){
                    String s=new String(b);
                    Log.e("s", s);

                    JsonFriend(s);
                }

                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);
            }
        }).start();
       return mSortList;

    }

    private void JsonFriend(String s) {
        try {
            JSONObject jsonObject=new JSONObject(s);
            JSONObject jsonObject1=jsonObject.getJSONObject("data");
            JSONArray jsonArray=jsonObject1.getJSONArray("FriendData");
            if (jsonArray.length()==0){
                Log.e("wu", "wu");
            }else {
                for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject2=jsonArray.getJSONObject(i);
                    SortModel sortModel = new SortModel();
                    String nickname=jsonObject2.getString("nickname");
                    sortModel.setNickname(nickname);
                    sortModel.setUserid(jsonObject2.getString("userid"));
                    sortModel.setTag(jsonObject2.getString("tag"));
                    String origin_nickname=jsonObject2.getString("origin_nickname");
                    sortModel.setOrigin_nickname(origin_nickname);
                    sortModel.setPhoto(jsonObject2.getString("photo"));
                    //汉字转换成拼音
                    if (nickname.equals("null")){
                       pinyin = characterParser.getSelling(origin_nickname);
                    }else {
                        pinyin = characterParser.getSelling(nickname);
                    }
                    Log.e("pinyin",pinyin);
                    String sortString = pinyin.substring(0, 1).toUpperCase();

                    // 正则表达式，判断首字母是否是英文字母
                    if(sortString.matches("[A-Z]")){
                        sortModel.setSortLetters(sortString.toUpperCase());
                    }else{
                        sortModel.setSortLetters("#");
                    }

                    mSortList.add(sortModel);

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                if (sortModel.getNickname().equals("null")){
                    name = sortModel.getOrigin_nickname();
                }else {
                    name = sortModel.getNickname();
                }
                Log.e("name",name);
                if (name.toUpperCase().indexOf(
                        filterStr.toString().toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }
}
